package com.polaris.live.ui.me

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.polaris.live.adapter.level.MeCharmRichBannerAdapter
import com.polaris.live.adapter.level.MeCharmRichLevelAdapter
import com.polaris.live.adapter.level.MeRichAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.ext.dp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.databinding.FragmentMeRichBinding
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.resp.back_resp.RichItemVo
import com.polaris.live.resp.bean.LevelUpRewardBean
import com.polaris.live.utils.RichCharmImgUtil
import com.polaris.live.viewmodel.me.RichCharmViewModel
import com.zhpan.indicator.enums.IndicatorSlideMode

/**
 * 壕等级
 *
 * @author Created by 半仙 on 2024/2/2/002 14:41
 */
class MeRichFragment : BaseVbFragment<RichCharmViewModel, FragmentMeRichBinding>() {

    private val mAdapter by lazy { MeRichAdapter() }

    private var mLevelAdapter: MeCharmRichLevelAdapter? = null

    private val mRewardList = mutableListOf<LevelUpRewardBean>()

    private val mBannerAdapter by lazy { MeCharmRichBannerAdapter() }

    private var nowRichLevel = 0 //当前等级

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        initUserData()
        mBinding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
            adapter = mAdapter
        }
        mLevelAdapter = MeCharmRichLevelAdapter(MeCharmRichLevelAdapter.RICH)
        mBinding.levelRecycler.apply {
            layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
            adapter = mLevelAdapter
        }
        mBinding.levelBanner.apply {
            registerLifecycleObserver(lifecycle)
            setAdapter(mBannerAdapter)
            setIndicatorSlideMode(IndicatorSlideMode.NORMAL)
            setIndicatorVisibility(View.GONE)
            setRoundCorner(12.dp)
            setAutoPlay(false)
            setCanLoop(false)
            registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    val isFirstItem = position == 0
                    val isLastItem = position == mBannerAdapter.itemCount - 1
                    mBinding.ivLeft.visibility = if (isFirstItem) View.GONE else View.VISIBLE
                    mBinding.ivRight.visibility = if (isLastItem) View.GONE else View.VISIBLE
                }
            })
        }
        mBinding.ivLeft.setOnSingleClickListener {
            val getNow = mBinding.levelBanner.currentItem
            if (getNow - 1 >= 0) {
                mBinding.levelBanner.setCurrentItem(getNow - 1, true)
            }
        }
        mBinding.ivRight.setOnSingleClickListener {
            val getNow = mBinding.levelBanner.currentItem
            if (getNow + 1 <= mBannerAdapter.itemCount) {
                mBinding.levelBanner.setCurrentItem(getNow + 1, true)
            }
        }
        mBinding.saveLanguage.setOnSingleClickListener {
            GlobalPopupManager.showRechargePopup(
                requireContext(),
                mViewModel,
                isNeedBottom = false,
                onRechargeOk = {
                    if (it == true) {
                        mViewModel.getUser()
                    }
                })
        }
        mViewModel.getRichCharmRule()
        initObserver()
    }

    private fun initUserData() {
        UserManager.getUser().account?.let {
            val (richLevel, richNextNum, richImage) = RichCharmImgUtil.getRichImg(it.richs)
            nowRichLevel = richLevel
            val richNum = RichCharmImgUtil.getRichNum(it.richs)

            mBinding.tvLevel.text = "Lv.${richLevel}"

            val currentLevel = if (richLevel >= 30) {
                richLevel - 1
            } else {
                richLevel
            }
            mBinding.tvLevelStart.text = "Lv.${currentLevel}"
            mBinding.tvLevelEnd.text = "Lv.${currentLevel + 1}"

            mBinding.ivRich.setImageResource(richImage)

            val rich = it.richs - richNum
            val totalRich = richNextNum - richNum
            if (totalRich > 0) {
                mBinding.progressBar.progress = ((rich * 100) / totalRich).toInt()
            } else {
                mBinding.progressBar.progress = 100
            }
            if (it.richs < richNextNum) {
                mBinding.tvDiamond.text = (richNextNum - it.richs).toString()
            } else {
                mBinding.tvDiamond.text = "0"
            }
        }
    }

    private fun initObserver() {
        mViewModel.mRichCharmLiveData.observe(this) { resultState ->
            mBinding.loadingView.visibility = View.GONE
            parseState(resultState, {
                mBinding.llBottom.visibility = View.VISIBLE
                val mutableList = ArrayList(it.richLevel)
                mutableList.forEach { cil ->
                    it.richLevelRewardExplains.forEach { (t, u) ->
                        if (t.toInt() == cil.level) {
                            val ls = mutableListOf<String>()
                            u.forEach { str ->
                                ls.add(str.title)
                                cil.privilege = ls
                            }
                        }
                    }
                }
                mutableList.add(RichItemVo(NOSHOW, NOSHOW))
                mutableList.add(RichItemVo(NOSHOW, NOSHOW))

                val sortedList = mutableListOf<LevelUpRewardBean>()
                it.richLevelRewardExplains.forEach { (t, u) ->
                    sortedList.add(LevelUpRewardBean(t.toInt(), u))
                }

                mRewardList.addAll(sortedList.sortedWith(compareBy { it.level }))

                mAdapter.setList(mutableList)



                mLevelAdapter?.setList(mRewardList)
                var data = mRewardList.getOrNull(0)?.rewardVo
                if (data == null) {
                    mBinding.llDressUp.visibility = View.GONE
                    return@parseState
                }
                if (nowRichLevel > 0) {
                    var showIndex = 0
                    mRewardList.forEachIndexed { index, levelUpRewardBean ->
                        if (levelUpRewardBean.level == nowRichLevel) {
                            showIndex = index
                        }
                    }
                    data = mRewardList.getOrNull(showIndex)?.rewardVo
                    mLevelAdapter?.setSelect(showIndex)
                    mBinding.levelRecycler.scrollToPosition(showIndex)
                }
                mBinding.levelBanner.create(data)
                isShowLeftRight()
            }, {
                mBinding.consDetail.visibility = View.GONE
                mBinding.errorView.visibility = View.VISIBLE
                mBinding.errorView.setText(it.errorMsg)
            })
        }
        mLevelAdapter?.setOnItemClickListener { adapter, view, position ->
            mLevelAdapter?.setSelect(position)
            val data = mRewardList.getOrNull(position)?.rewardVo ?: return@setOnItemClickListener
            mBinding.levelBanner.create(data)
            isShowLeftRight()
        }
        mViewModel.mUserLiveData.observe(this) { resultState ->
            parseState(resultState, {
                UserManager.setUser(it)
                initUserData()
            })
        }
    }

    private fun isShowLeftRight() {
        if (mBannerAdapter.itemCount <= 1) {
            mBinding.ivLeft.visibility = View.GONE
            mBinding.ivRight.visibility = View.GONE
        } else {
            mBinding.ivRight.visibility = View.VISIBLE
        }
    }

    companion object {

        const val NOSHOW = -1
    }

}